package com.csun.cmny.provider.resolver;

import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Objects;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-01-18 11:59
 * @Description: the cmny message source
 */
@Slf4j
@Component
public class CmnyMessageSource {

    @Resource
    private MessageSource messageSource;
//    @Autowired
//    private HttpServletRequest request;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

//    private static final String HEADER_LANGUAGE = "Accept-Language";

    @Resource
    private CmnyLocaleResolver cmnyLocaleResolver;

    public String getMessage(String code, Object[] param, String language) {

        Locale locale = LocaleContextHolder.getLocale();
        if (PublicUtil.isNotEmpty(language)) {
            String[] languages = language.split("_");
            if (languages.length == 2) {
                locale = new Locale(languages[0], languages[1]);
                log.debug("current local = {}", locale.toString());
            }
        }

        return messageSource.getMessage(code, param, locale);
    }

    public String getMessage(String code, Object[] param) {
        Locale locale = LocaleContextHolder.getLocale();
        log.info("local = {}", locale.toString());
        return messageSource.getMessage(code, param, LocaleContextHolder.getLocale());
    }

    /**
     * get code message by group id
     *
     * @param code      the code
     * @param params    the params
     * @param groupId   the group id
     *
     * @return  the code message
     */
    public String getMessage(String code, Object[] params, Long groupId) {

        String language = (String) redisTemplate.opsForValue().get(RedisKeyUtil.getUacGroupLanguageId(groupId));
        Locale locale = Locale.getDefault();
        if (PublicUtil.isNotEmpty(language)) {
            String[] languages = language.split("_");
            if (languages.length == 2) {
                locale = new Locale(languages[0], languages[1]);
                log.debug("current local = {}", locale.toString());
            }
        }
        log.info("====> language = {}", locale.toString());
        try {
            return messageSource.getMessage(code, params, locale);
        } catch (Exception e) {
            log.error("===> 需要配置本地化消息 code = {}", code);
            return null;
        }

    }

}
